package com.zndroid.utils.impl;

/**
 * @author lzy
 */
@SuppressWarnings("unused")
public class StringUtil {
    /**
     * byte -> hex
     * @param src bytes
     * @return Hex string
     * */
    public String byte2HexString(byte[] src) {
        return byte2HexString(src, false);
    }

    /**
     * byte -> hex
     * @param src bytes
     * @param isPrefix "0x" prefix
     * @return Hex string
     * */
    public String byte2HexString(byte[] src, boolean isPrefix) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return "";
        }

        if (isPrefix) {
            stringBuilder.append("0x");
        }

        char[] buffer = new char[2];
        for (byte b : src) {
            buffer[0] = Character.toUpperCase(Character.forDigit((b >>> 4) & 0x0F, 16));
            buffer[1] = Character.toUpperCase(Character.forDigit(b & 0x0F, 16));
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }

    /**
     * Hex string -> bytes
     *
     * @param hex hex string
     * @return byte[]
     * */
    public byte[] hexString2Byte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] c = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(c[pos]) << 4 | toByte(c[pos + 1]));
        }
        return result;
    }

    private int toByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}
